package com.fan.shop.global;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.ResourceBundle;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

public class ShopGlobalUtils {

	private static volatile ShopGlobalUtils instance = null;

	private ShopGlobalUtils() {
		super();
		instance = new ShopGlobalUtils();
	}

	public static ShopGlobalUtils getInstance() {
		if (instance == null) {
			synchronized (ShopGlobalUtils.class) {
				if (instance == null) {
					instance = new ShopGlobalUtils();
				}
			}
		}
		return instance;
	}

	public static String getMessage(String key) {
		FacesContext facesContext = FacesContext.getCurrentInstance();
		String messageBundleName = facesContext.getApplication()
				.getMessageBundle();
		ResourceBundle messageBundle = ResourceBundle
				.getBundle(messageBundleName);
		String value = messageBundle.getString(key);

		return value;
	}

	public static void addErrorMessage(String msg) {
		addMessage(FacesMessage.SEVERITY_ERROR, msg);
	}

	private static void addMessage(FacesMessage.Severity severity, String msg) {
		final FacesMessage facesMsg = new FacesMessage(severity, msg, msg);
		FacesContext.getCurrentInstance().addMessage(null, facesMsg);
	}

	public static void addSuccessMessage(String msg) {
		addMessage(FacesMessage.SEVERITY_INFO, msg);
	}
	
	public static String getDateTimeString(Date date)
	{
		DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
		String result = df.format(date);
		return result;
	}
	
	
	public static String getFileSuffix(String contentType)
	{
		if(contentType.equalsIgnoreCase("image/jpeg"))
		{
			return ".jpg";
		}
		if(contentType.equalsIgnoreCase("image/bmp"))
		{
			return ".bmp";
		}
		if(contentType.equalsIgnoreCase("image/gif"))
		{
			return ".gif";
		}
		if(contentType.equalsIgnoreCase("image/png"))
		{
			return ".png";
		}
		return "";
	}
	
	public static String getFileContentType(String filename)
	{
		String fileName = filename.toLowerCase();
		if(fileName.toLowerCase().endsWith(".jpg") || fileName.endsWith("jpeg") || fileName.endsWith("jpe"))
		{
			return "image/jpeg";
		}
		if(fileName.toLowerCase().endsWith(".bmp") || fileName.endsWith("bm") )
		{
			return "image/bmp";
		}
		if(fileName.toLowerCase().endsWith(".gif")  )
		{
			return "image/gif";
		}
		if(fileName.toLowerCase().endsWith(".png")  )
		{
			return "image/png";
		}
		
		return null;
	}
	
	public static String getSuffix(String filename)
	{
		if(filename.contains("."))
		{
			return filename.substring(  filename.lastIndexOf("."));
		}
		else
		{
			return "";
		}
	}
}
